JS - 數值欄位加總計算

效果:
下圖中,Monthly Base Salary + Allowance 會自動帶出 Total 的值,並加上千位分隔符(group seperator、三位一撇)。
(Monthly Base Salary以及Allowance可以輸入帶有千位分隔符或純數字的形式)

前端頁面 => 即時改變加總欄位(Total)中的值,並加上千位分隔符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<tr>
<td>Monthly Base Salary: </td>
<td>
NT$ <input type="text" value="" style="width:200px" name="base_salary" id="base_salary" onchange="change_total()" >
<input type="hidden" name="orig_base_salary" value="">
</td>
</tr>
<tr>
<td>Allowance: </td>
<td>
NT$ <input type="text" value="" style="width:200px" name="allowance" id="allowance" onchange="change_total()" >
<input type="hidden" name="orig_allowance" value="">
</td>
</tr>
<tr>
<td>Total: </td>
<td>
NT$ <input type="text" value="" style="width:200px" name="total" id="total" readonly>
<input type="hidden" name="orig_total" value="">
</td>
</tr>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
/* 加上數字標記 */
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
function change_total(){
var base_salary = $('#base_salary').val().replace(/,/g, ''); // 若有千位分隔符就replace掉,方便做數字加總
var allowance = $('#allowance').val().replace(/,/g, '');
var total = base_salary*1 + allowance*1;
total = commaSeparateNumber(total); // 加總結束,把值再加上千位分隔符
$("#total").val(total);
}
</script>

儲存時,存於資料庫的是沒有千位分隔符的,單純只有數字(注意欄位型態)。
下次取出時,把存在資料庫的值加上千位分隔符。

  • 送至後端儲存時 => 把千位分隔符拿掉,存入資料庫中:

    1
    2
    3
    $_POST['base_salary'] = str_replace(',', '', $_POST['base_salary']);
    $_POST['allowance'] = str_replace(',', '', $_POST['allowance']);
    $_POST['total'] = str_replace(',', '', $_POST['total']);
  • 下次取出時,幫數字加上分隔符:

    1
    2
    3
    $item['base_salary'] = number_format($item['base_salary'], 0, ".", ",");
    $item['allowance'] = number_format($item['allowance'], 0, ".", ",");
    $item['total'] = number_format($item['total'], 0, ".", ",");